package com.itheima.controller;



import com.itheima.pojo.Admin;
import com.itheima.service.AdminService;
import com.itheima.vo.AdminVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/system/users")

public class AdminControrller {


    @Autowired
    AdminService adminService;

    /**
     * 发送验证码
     *
     * @return
     */
    @GetMapping("verification")
    public ResponseEntity<String> Sendverificationcode() {
        String verificationcode = adminService.random();
        try {
            if (StringUtils.isNotEmpty(verificationcode)) {

                return ResponseEntity.ok(verificationcode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 用户登录
     *
     * @param pram
     * @return
     */
    @RequestMapping("login")
    public ResponseEntity<String> login(@RequestBody Map<String,String> pram) {
        String username = pram.get("username");
        String password=pram.get("password");
        String code=pram.get("code");
        String token = adminService.login(username, password, code);
        try {
            if (StringUtils.isNotEmpty(token)) {
                return ResponseEntity.ok(token);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 获取用户信息
     *
     * @param token
     * @return
     */
    @GetMapping("profile")
    public ResponseEntity<AdminVo> UserInfo(@RequestHeader("Authorization") String token) {

        AdminVo adminVo = adminService.AdminInfo(token);

        try {
            if (null != adminVo) {
                return ResponseEntity.ok(adminVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }


    /**
     * 校验token，根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public Admin queryUserByToken(@PathVariable("token") String token) {
        return this.adminService.queryUserByToken(token);
    }

}

